<?php
declare (strict_types=1);

namespace app\service;

use think\App;
use app\model\CookieModel;

class CookieManagerService extends \think\Service
{
    public function __construct(App         $app,
                                CookieModel $cookieModel)
    {
        parent::__construct($app);
        $this->cookieModel = $cookieModel;
    }

    function save($url, $cookie)
    {
        $cookie_id = crc64($cookie);
        $host = static::parseUrl($url);
        $this->cookieModel->replace()->save(compact('cookie_id', 'host', 'cookie'));
    }

    static function parseUrl($url)
    {
        $url = filter_var($url, FILTER_VALIDATE_URL);
        thow_if(!$url, 'url is not valid');
        $arr = parse_url($url);
        return $arr['host'];
    }

    function listCookieByUrl($url)
    {
        $host = static::parseUrl($url);
        $rs = $this->where('host', $host)
            ->where('state', CookieModel::STATE_OK)
            ->select();
    }
}
